var gQueryType = 1;
var gAjaxObject;
var gAjaxTime;
var gLastNum = "";
var gSelectKeywordIndex = -1;
var copyNotfindReady = 0;
var querycookie = "";
var clickmark=0;
//优先执行匿名函数
(function () {
    var postid = $("#postid");
    var nu = GetQueryString("nu");
    if (nu != null && nu != "") {
        postid.val(nu);
        query();
    }

    //input location
    $.ajax({
        type: "post",
        url: "/sysapi.do",
        data: "method=findxzqbyip",
        dataType: "json",
        success: function (resultJson) {
            if (resultJson.fullName != null && resultJson.fullName != "") {
                var fullName = resultJson.fullName;
                $(".current-city").text(fullName.substring(fullName.lastIndexOf(",") + 1));
                $("#location").addClass("btn-location").click(function () {
                    postid.val(fullName.replace(/,/g, ""));
                });
            }
        }
    });

    //example nu
    $.ajax({
        type: "post",
        url: "/sysapi.do",
        data: "method=demonu",
        success: function (result) {
            $("#useTips").text(result);
        }
    });

})();
//页面载入后执行
$(function () {
    var shownotime=getcookie("shownotime");
    if(shownotime!=1&&$(".surprise-bigbox").is(':visible')){
        startAnimation();
    }else{
        $(".surprise-bigbox").css({
            "transition":"all 0.1s linear",
            " -moz-transition":"all 0.1s linear",
            "-webkit-transition":"all 0.1s linear",
            "-o-transition":"all 0.1s linear"
        })
        $(".surprise-bigbox").css("z-index","2");
    };
    var postid = $("#postid");
    var reg = new RegExp("[0-9a-zA-Z]{4,}");
    postid.keyup(function (e) {
        var keycode = e.keyCode ? e.keyCode : e.which;
        //回车查询
        if (keycode != 13) {
            var keyword = postid.val();
            if (keyword != "") {
                if (keyword != gLastNum) {
                    clearTimeout(gAjaxTime);
                    gAjaxTime = setTimeout("getKeyword()", 200);
                }
            } else {
                clearTimeout(gAjaxTime);
                $("#inputTips").hide();
                gSelectKeywordIndex = -1;
            }
        }
    }).keydown(function (e) {
        var keycode = e.keyCode ? e.keyCode : e.which;
        var keyword = postid.val();
        //key up & down
        if (keycode == 40 && keyword != "" && reg.test(keyword)) {
            if (!$("#inputTips").is(":hidden")) {
                if (gSelectKeywordIndex == -1) {
                    gSelectKeywordIndex = 0;
                } else if (gSelectKeywordIndex == $("#inputTips li.selection:last").attr("data-index")) {
                    gSelectKeywordIndex = 0;
                } else {
                    gSelectKeywordIndex++;
                }
                $("#inputTips li.selection").removeClass("hover");
                $("#inputTips li.selection:eq(" + gSelectKeywordIndex + ")").addClass("hover");
            }
        } else if (keycode == 38 && keyword != "" && reg.test(keyword)) {
            if (!$("#inputTips").is(":hidden")) {
                if (gSelectKeywordIndex == -1) {
                    gSelectKeywordIndex = $("#inputTips li.selection:last").attr("data-index");
                } else if (gSelectKeywordIndex == 0) {
                    gSelectKeywordIndex = $("#inputTips li.selection:last").attr("data-index");
                } else {
                    gSelectKeywordIndex--;
                }
                $("#inputTips li.selection").removeClass("hover");
                $("#inputTips li.selection:eq(" + gSelectKeywordIndex + ")").addClass("hover");
            }
        }
    }).click(function (e) {
        var num = $("#postid").val().Trim();
        e.stopPropagation();
        if (num == "") {
            getqueryHistory();
        }else if(num.length>=5){
            clearTimeout(gAjaxTime);
            gAjaxTime = setTimeout("getKeyword()", 200);
        }
    }).bind('input propertychange', function() {
        var keyword = postid.val();
        if(keyword == ""){
            postid.css("font-size","16px")
        }else{
            postid.css("font-size","22px")
        }
    });
    function startAnimation() {
        $(".surprise-bigbox").css("right","700px");
        $(".surprise-bigbox").css("top","0px");
        setTimeout(function () {
            if(clickmark==0){
                startAnimation1();
            }
        },6000)
    }
    function startAnimation1() {
        $(".surprise-bigbox").css("right","350px");
        $(".surprise-bigbox").css("top","-150px");
        setTimeout(function () {
            if(clickmark==0){
                startAnimation2();
            }
        },6000)

    }
    function startAnimation2() {
        $(".surprise-bigbox").css("right","20px");
        $(".surprise-bigbox").css("top","160px");
        setTimeout(function () {
            if(clickmark==0){
                startAnimation();
            }
        },6000)

    }
    $(".surprise-bigbox").click(function () {
        clickmark=1;
        var shownotime=getcookie("shownotime");
        if(shownotime==1){
            clickmark=0;
            $(".surprise-bigbox").css({
                "transition":"all 5s linear",
                " -moz-transition":"all 5s linear",
                "-webkit-transition":"all 5s linear",
                "-o-transition":"all 5s linear",
                "z-index":100
            })
            startAnimation();
            deleteCookie("shownotime");
        }else{
            $(".surprise-bigbox").css({
                "transition":"all 0.1s linear",
                " -moz-transition":"all 0.1s linear",
                "-webkit-transition":"all 0.1s linear",
                "-o-transition":"all 0.1s linear"
            })
            $(".surprise-bigbox").css("right","20px");
            $(".surprise-bigbox").css("top","160px");
            $(".surprise-bigbox").css("z-index","2");
            setcookie("shownotime",1);
        }
    })
    //监听查询框粘贴事件
    $.fn.pasteEvents = function( delay ) {
        if (delay == undefined) delay = 20;
        return $(this).each(function() {
            var $el = $(this);
            $el.on("paste", function() {
                $el.trigger("prepaste");
                setTimeout(function() { $el.trigger("postpaste"); }, delay);
            });
        });
    };
    $("#postid").on("postpaste", function() {
        var num = $("#postid").val().Trim();
        gLastNum = num;
        if (gLastNum.length < 5){
            return false;
        }
        $.ajax({
            type: "post",
            url: "/autonumber/autoComNum?text=" + num,
            dataType:"json",
            success:function(resultJson) {
                $("#postid").val(resultJson.num).select();
                gSelectKeywordIndex = -1;
                if (resultJson.auto && resultJson.auto.length > 0) {
                    $("#inputTips").show();
                } else {
                    $("#inputTips").hide();
                }
                addSuggestion(resultJson);
            }
        });
    }).pasteEvents();
    $(document).click(function () {
        if (!$("#inputTips").is(":hidden")) {
            $("#inputTips").hide();
        }
    });
    $("#query").click(query);

    //input tips
    $("#inputTips").delegate("li.selection", "mouseenter", function () {
        $("#inputTips li").removeClass("hover");
        $(this).addClass("hover");
        gSelectKeywordIndex = $(this).attr("data-index");
    }).delegate("li.selection", "click", function () {
        postid.val($(this).text()).css({"color":"#323232","font-size":"22px"}).focus();
        var code=$(this).attr("data-code");
        $("#selectComBtn img").attr("data-code",code)
        query();
    }).delegate("a.delhistory", "click", function (e) {var code = $(this).parent().attr("data-code");
        var nu= $(this).parent().attr("data-num");
        var history = querycookie;
            for (var i = 0; i < history.length && i < 10; i++) {
                if (history[i].nu == nu && history[i].code == code) {
                    history.splice(i, 0);
                    queryHistoryFrame.attr("src", "//cache.kuaidi100.com/index.html?option=remove&gCompanyCode=" + history[i].code + "&gKuaidiNumber=" + history[i].nu);
                }
            }
            $(this).parent().remove();
            e.stopPropagation();
    });
    $("#delList").live("click", function () {
        //kdHistory.empty();
        queryHistoryFrame.attr("src", "//cache.kuaidi100.com/index.html?option=empty");
        $("#inputTips li").remove();
        $("#inputTips").hide();
    })
    $("#useTips").click(function () {
        postid.val($(this).text()).css({"color":"#323232","font-size":"22px"}).trigger("click");
    });
    $("#useTips2").click(function () {
        postid.val($(this).text()).css({"color":"#323232","font-size":"22px"});
    });

    //open selectCom
    $("#selectComBtn").click(function () {
        if (gAjaxGet) {
            gAjaxGet.abort();
        }
        $("#errorTips").hide();
        $("#example").hide()
        $("#queryWait").hide()
        $("#resultHeader").hide();
        $("#queryContext").hide();
        $("#queryPs").hide();
        $("#notFindTip").hide()
        $("#shareBox").hide()
        $("#comList").toggle();
        _hmt.push(['_trackEvent', "company", "company-open"]);
    });

    //click selectCom
    $("#comList .com-list").delegate("a", "click", function () {
        if($(this).attr("data-code")=="default"){
            $("#selectComBtn img").attr("src","https://cdn.kuaidi100.com/images/all/56/default.png");
            $("#comList").hide();
        }else{
            var num = postid.val();
            if (gLoading == 1) return;
            hideTips();
            $("#comList").hide();
            gSelectKeywordIndex = -1;
            var companyCode = $(this).attr("data-code");
            gCompanyCode=companyCode;
            if (companyCode != null && companyCode != "") {
                $("#selectComBtn img").attr("data-code", companyCode);
                selectCompanyByCode($(this).attr("data-code"));
                if (num != "") {
                    if (validateKuaidiNumber()) {
                        getResult(gCompanyCode, $("#postid").val().Trim());
                    }
                }
            }
        }
    });

    //rss
    $("#rssBtn").click(function () {
        setcookie_kuaidi100("addcom",gCompanyCode);
        setcookie_kuaidi100("addnu",gKuaidiNumber);
        window.location.href = "//buyer.kuaidi100.com";
    });

    //share
    $("#shareBtn").click(function () {
        openSenBox();
        $("#shareBox").show();
        $("#sendHistory").css("margin-top", ($(window).height() - 120) / 2 + "px");
    });
    $("#shareClose").click(function () {
        closeHisCtrl();
        $("#shareBox").hide();
    });
	
	//print
   $("#printBtn").click(function () {
        $("#orderPrint").show();
        $("#companyName").addClass("font16px");
        $("#companyNum").addClass("font16px");
        var queryResult=document.getElementById('orderPrint').innerHTML + "<br/>" + document.getElementById('resultTop').innerHTML + "<br/>" + document.getElementById('queryResult').innerHTML;
        $("#orderPrint").hide();
        var newwindow = window.open("","_blank");
        newwindow.window.document.head.innerHTML='<link rel="stylesheet" href="https://cdn.kuaidi100.com/css/query_v4.css?version=201611181610" />';
        newwindow.window.document.body.innerHTML = queryResult;
       setTimeout(function () {
           newwindow.window.print();
       }, 50);

    })
    //package
    $(".cloud").click(function () {
        var _that = $(this);
        _that.addClass("cloud-fly");
        setTimeout(function () {
            _that.addClass("cloud-hide");
        }, 200);
    });
});

//autonumber
function getKeyword() {
    var num = $("#postid").val().Trim();
    gLastNum = num;
    if (gLastNum.length < 5) {
        return false;
    }
    if (gAjaxObject) {
        gAjaxObject.abort();
    }
    gAjaxObject = $.ajax({
        type: "post",
        url: "/autonumber/autoComNum?text=" + num,
        dataType: "json",
        success: function (resultJson) {
            gSelectKeywordIndex = -1;
            addSuggestion(resultJson);
        }
    });
}

//autonumber selection
function addSuggestion(resultJson) {
    $("#suggestList").empty();
    $("#inputTips").empty();
    var i = 0;
    var num = resultJson.num;
    if (resultJson.auto && resultJson.auto.length > 0) {
        $("#suggestList").append("<span class=\"li-title\">推荐</span>");
        for (i = 0; i < resultJson.auto.length; i++) {
            var comCode = resultJson.auto[i].comCode;
            for (var j in jsoncom.company) {
                if (comCode == jsoncom.company[j].number) {
                    $("#suggestList").append("<a data-code=\"" + comCode + "\" data-num=\"" + num + "\">" + jsoncom.company[j].shortName + "</a>");
                    if (i <= 2) {
                        $("#inputTips").append("<li class=\"selection selection" + i + "\" data-index=\"" + i + "\" data-code=\"" + comCode + "\" data-num=\"" + num + "\"><span>" + num + "</span>" + jsoncom.company[j].name + "</li>");
                    }
                }
            }
        }
        if (i > 2) i = 3;
        $("#inputTips").show();
    } else {
        $("#inputTips").hide();
    }
    $("#inputTips").append("<li class=\"selection selection" + i + "\" data-index=\"" + i + "\" data-code=\"other\" title=\"识别有误？请手动选择！\"><span>" + num + "</span>其它快递</li>");
    $("#inputTips").append("<li class=\"tips_bottom\">快递100大数据为您提供智能识别</li>");
    $("#suggestList").show();
}
//history
function jsoncallback(data) {
    querycookie = eval('(' + decodeURIComponent(data) + ')');
    gethistory(querycookie);
}
function getqueryHistory() {
    $.ajax({
        url: "//cache.kuaidi100.com/querycookie.jsp",
        type: "GET",
        dataType: 'jsonp',
        jsonp: 'jsoncallback'
    });
    return true;
}
function gethistory(querycookie) {
    var history = querycookie;
    $("#inputTips").empty();
    $("#inputTips").hide();
   // queryHistoryFrame.attr("src", "//cache.kuaidi100.com/index.html?option=all");
    //var history = kdHistory.all();
    if (history != null && history != "") {
        $("#inputTips").show();
        // $("#suggestList").append("<span class=\"li-title\">推荐</span>");
        for (var i = 0; i < history.length && i < 10; i++) {
            for (var j in jsoncom.company) {
                if (history[i].code == jsoncom.company[j].number) {
                    $("#inputTips").append("<li class=\"selection selection" + i + "\" data-index=\"" + i + "\" data-code=\"" + history[i].code + "\" data-num=\"" + history[i].nu + "\"><a title=\"删除\" class=\"hidden delhistory\"></a><span>" + history[i].nu + "</span>" + jsoncom.company[j].name + "</li>");
                }
            }
        }
        if (getcookie("TOKEN") && getcookie("loginSession") == "1") {
            $("#inputTips").append("<li class=\"histips_bottom\"><a class=\"del-list\" id=\"delList\">全部清除</a>最近十条查询记录。<a class=\"login-tips\" href=\"//" + getcookie("loginType") + ".kuaidi100.com/index.shtml\">查看更多&gt;&gt;</a></li>");
        } else {
            $("#inputTips").append("<li class=\"histips_bottom\"><a class=\"del-list\" id=\"delList\">全部清除</a>最近十条查询记录。需要永久保存？更多功能？<a class=\"login-tips\" href=\"http://sso.kuaidi100.com/\">马上登录试试</a></li>");
        }
    }
}
//query
function query() {
    $("#postid").blur();
    //查询订阅按钮控制
    var loginType=getcookie("loginType")
    if(loginType=="BUYER"){
        $("#rssBtn").show();
    }
    var loginMobile=getcookie("loginMobile");
    if(loginMobile==""||loginMobile=="null"){
        $("#bindBtn").show();
    }
    if (gLoading == 1) return;
    //$("#selectComBtn").attr("disabled","disabled");
    var num = $("#postid").val().Trim();
    var reg = new RegExp("[0-9a-zA-Z]{4,}");
    if (num == "") {
        $("#errorTips").show();
        $("#errorMessage").html("请输入快递单号。");
        $("#postid").focus();
    } else if (reg.test(num)) {
        gQueryResult = 0;
        clearTimeout(gAjaxTime);
        $("#comList").hide();
        $("#errorTips").hide();
        $("#example").hide();
        $("#resultHeader").hide();
        $("#queryContext").hide();
        $("#queryPs").hide();
        $("#notFindTip").hide();
        $("#shareBox").hide();
        if (gSelectKeywordIndex >= 0) {
            //控制输入框中的下拉的快递公司
            var selection = $("#inputTips li.selection:eq(" + gSelectKeywordIndex + ")");
            var code = selection.attr("data-code");
            if (code != "other") {
                selectCompanyByCode(code);
                $("#postid").val(selection.attr("data-num"));
                if (validateKuaidiNumber()) {
                    getResult(gCompanyCode, selection.attr("data-num"));
                }
                _hmt.push(['_trackEvent', "autoCom", "click"]);
            } else {
                $("#postid").val(selection.find("span").text());
                $("#comList").show();
                _hmt.push(['_trackEvent', "otherCom", "click"]);
            }
        }else{
            gLastNum = num;
            $("#inputTips").hide();
            $(".logo-model").show();
            //$("#queryWait").show();
            if (gAjaxObject) {
                gAjaxObject.abort();
            }
            gLoading = 1;
            var companyCode=$("#selectComBtn img").attr("data-code");
           if(companyCode=="default"){
               gAjaxObject = $.ajax({
                   type: "post",
                   url: "/autonumber/autoComNum?text=" + num,
                   dataType: "json",
                   success: function (resultJson) {
                       gLoading = 0;
                       $(".logo-model").hide();
                       //$("#queryWait").hide();
                       if (resultJson.comCode || (resultJson.auto && resultJson.auto.length > 0)) {
                           var comCode = resultJson.comCode ? resultJson.comCode : resultJson.auto[0].comCode;
                           selectCompanyByCode(comCode);
                           $("#postid").val(resultJson.num);
                           if (validateKuaidiNumber()) {
                               getResult(gCompanyCode, resultJson.num);
                           }
                           $("#notFindRight").show();
                       } else {
                           $("#postid").select();
                           $("#queryContext").hide();
                           $("#selectComBtn img").attr("src", "https://cdn.kuaidi100.com/images/all/56/default.png");
                           $("#resultHeader").hide();
                           $("#notFindTip").show();
                           $("#notFindRight").hide();
                       }
                   },
                   error: function () {
                       gLoading = 0;
                   }
               });
           }else{
               gLoading = 0;
               $(".logo-model").hide();
               $("#queryWait").hide();
               gCompanyCode=companyCode;
               selectCompanyByCode(companyCode);
               $("#postid").val(num);
               if (validateKuaidiNumber()) {
                   getResult(gCompanyCode, num);
               }
           }

            _hmt.push(['_trackEvent', "query", "click"]);
        }
        gSelectKeywordIndex = -1;
    } else {
        window.open("https://www.kuaidi100.com/courier/?searchText=" + encodeURIComponent(num));
    }
}